from flask import Blueprint, jsonify, request
from ..models.airport import Airport
from ..models.runway import Runway
from ..models.parking_apron import ParkingApron
from ..models.oil_tank import OilTank
from ..models.ammunition_depot import AmmunitionDepot
from .. import db

bp = Blueprint('airports', __name__, url_prefix='/api/airports')

@bp.route('/', methods=['GET'])
def get_all_airports():
    """获取所有机场"""
    airports = Airport.query.all()
    result = []
    
    for airport in airports:
        airport_data = airport.to_dict()
        
        # 获取该机场的跑道信息
        runways = Runway.query.filter_by(airport_id=airport.id).all()
        airport_data['runways'] = [runway.to_dict() for runway in runways]
        
        result.append(airport_data)
    
    return jsonify(result)

@bp.route('/<int:airport_id>', methods=['GET'])
def get_airport(airport_id):
    """获取单个机场详情"""
    airport = Airport.query.get_or_404(airport_id)
    result = airport.to_dict()
    
    # 获取设施数量
    runway_count = Runway.query.filter_by(airport_id=airport_id).count()
    apron_count = ParkingApron.query.filter_by(airport_id=airport_id).count()
    oil_count = OilTank.query.filter_by(airport_id=airport_id).count()
    ammo_count = AmmunitionDepot.query.filter_by(airport_id=airport_id).count()
    
    # 添加设施数量到结果中
    result['facilitiesCount'] = runway_count + apron_count + oil_count + ammo_count
    result['runwayCount'] = runway_count
    result['apronCount'] = apron_count
    result['oilTankCount'] = oil_count
    result['ammunitionDepotCount'] = ammo_count
    
    result['hasRunways'] = runway_count > 0
    result['hasAprons'] = apron_count > 0
    result['hasOilTanks'] = oil_count > 0
    result['hasAmmunitionDepots'] = ammo_count > 0
    
    # 包含详细的设施列表
    runway_details = Runway.query.filter_by(airport_id=airport_id).all()
    apron_details = ParkingApron.query.filter_by(airport_id=airport_id).all()
    oil_details = OilTank.query.filter_by(airport_id=airport_id).all()
    ammo_details = AmmunitionDepot.query.filter_by(airport_id=airport_id).all()
    
    result['runways'] = [runway.to_dict() for runway in runway_details]
    result['parkingAprons'] = [apron.to_dict() for apron in apron_details]
    result['oilTanks'] = [oil.to_dict() for oil in oil_details]
    result['ammunitionDepots'] = [ammo.to_dict() for ammo in ammo_details]
    
    return jsonify(result)

@bp.route('/', methods=['POST'])
def create_airport():
    """创建机场"""
    data = request.json
    
    # 验证必要字段
    required_fields = ['name', 'region', 'latitude', 'longitude', 'hangar_capacity', 
                      'shelter_capacity', 'mask_capacity', 'cave_capacity', 'mask_count',
                      'total_capacity', 'aircraft_count', 'parking_apron_count', 
                      'w_field', 'l_field', 'i_field', 't_field', 'p_field', 'c_field']
    
    for field in required_fields:
        if field not in data:
            return jsonify({"error": f"Missing required field: {field}"}), 400
    
    # 创建机场
    new_airport = Airport(
        name=data['name'],
        region=data['region'],
        latitude=data['latitude'],
        longitude=data['longitude'],
        hangar_capacity=data['hangar_capacity'],
        shelter_capacity=data['shelter_capacity'],
        mask_capacity=data['mask_capacity'],
        cave_capacity=data['cave_capacity'],
        mask_count=data['mask_count'],
        total_capacity=data['total_capacity'],
        aircraft_count=data['aircraft_count'],
        parking_apron_count=data['parking_apron_count'],
        w_field=data['w_field'],
        l_field=data['l_field'],
        i_field=data['i_field'],
        t_field=data['t_field'],
        p_field=data['p_field'],
        c_field=data['c_field']
    )
    
    db.session.add(new_airport)
    db.session.commit()
    
    return jsonify(new_airport.to_dict()), 201

@bp.route('/<int:airport_id>', methods=['PUT'])
def update_airport(airport_id):
    """更新机场"""
    airport = Airport.query.get_or_404(airport_id)
    data = request.json
    
    # 更新机场
    for key, value in data.items():
        if hasattr(airport, key):
            setattr(airport, key, value)
    
    db.session.commit()
    
    return jsonify(airport.to_dict())

@bp.route('/<int:airport_id>', methods=['DELETE'])
def delete_airport(airport_id):
    """删除机场"""
    airport = Airport.query.get_or_404(airport_id)
    db.session.delete(airport)
    db.session.commit()
    
    return '', 204 